/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.community.controller.evaluation.analyze;

import cn.ac.nercis.pes.common.constant.evaluation.EvaluationModule;
import cn.ac.nercis.pes.common.constant.knowledge.TargetType;
import cn.ac.nercis.pes.common.constant.project.FinishState;
import cn.ac.nercis.pes.community.component.controls.MenuListCell;
import cn.ac.nercis.pes.community.component.dialog.MessageDialog;
import cn.ac.nercis.pes.community.component.dialog.MessageType;
import cn.ac.nercis.pes.community.controller.base.InitEvalDataLoad;
import cn.ac.nercis.pes.community.controller.evaluation.analyze.correction.EvalCorrectionController;
import cn.ac.nercis.pes.community.model.vo.MenuVO;
import cn.ac.nercis.pes.community.utils.AppStore;
import cn.ac.nercis.pes.community.utils.ControlUtils;
import cn.ac.nercis.pes.community.utils.LogUtils;
import cn.ac.nercis.pes.community.utils.SpringUtils;
import cn.ac.nercis.pes.community.views.evaluation.analyze.correction.EvalCorrectionView;
import cn.ac.nercis.pes.model.dto.project.SystemProcessDTO;
import cn.ac.nercis.pes.model.dto.target.LayerTargetDTO;
import cn.ac.nercis.pes.service.project.SystemProcessService;
import cn.ac.nercis.pes.service.project.SystemTargetService;
import javafx.application.Platform;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.net.URL;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.ResourceBundle;
import java.util.concurrent.CompletableFuture;

/**
 * 结果修正管理控制器
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
public class ResultCorrectionController implements Initializable, InitEvalDataLoad {
    @FXML
    private StackPane page;
    @FXML
    private BorderPane resultCorrectionPane;
    @FXML
    private AnchorPane emptyPane;
    @FXML
    private ImageView emptyImageView;
    @FXML
    private Label emptyLabel;
    @FXML
    private ListView<MenuVO> tecMenus;
    @FXML
    private ListView<MenuVO> manageMenus;

    private final SystemTargetService systemTargetService;
    private final SystemProcessService systemProcessService;

    private String currentSystemId;
    private MenuVO currentLayerTarget;
    private final BooleanProperty enablePaste = new SimpleBooleanProperty(false);

    public ResultCorrectionController() {
        this.systemTargetService = SpringUtils.getBean(SystemTargetService.class);
        this.systemProcessService = SpringUtils.getBean(SystemProcessService.class);
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        ControlUtils.initEmptyImageView(this.emptyImageView,log);
        this.initializeControl();
    }

    @Override
    public void initializeData(String systemId){
        LogUtils.info(log, "初始化结果修正...");
        this.currentSystemId = systemId;
        var evalCorrectionView = AppStore.getEvaluationView(this.currentSystemId, EvalCorrectionView.class);
        resultCorrectionPane.setCenter(Objects.requireNonNull(evalCorrectionView).load());
        loadMenuData();
    }

    public void setLayerFinishState(@NonNull MenuVO layerTarget, @NonNull FinishState state) {
        EvaluationModule module = EvaluationModule.fromNameByOverallEval(layerTarget.getTitle());
        LogUtils.info(log, "设置测评进度信息...");
        LogUtils.record(log, "请求数据，systemId：{},module:{},state:{}", this.currentSystemId, module, state);
        CompletableFuture.supplyAsync(() -> systemProcessService.setSystemProcess(this.currentSystemId, module, state))
                .thenAccept(res -> Platform.runLater(() -> {
                    if (res.isSuccess()) {
                        refreshLayerFinishState(layerTarget, state);
                    } else {
                        MessageDialog.builder()
                                .withContainer(this.page)
                                .withType(MessageType.FAIL).withMessage(res.getMsg())
                                .build().show();
                    }
                }))
                .exceptionally((ex) -> {
                    log.error("设置测评进度信息出错!", ex);
                    return null;
                });
    }

    private void refreshLayerFinishState(MenuVO layerTarget, FinishState state) {
        layerTarget.setIcon(ControlUtils.finishStateToIcon(state));
        layerTarget.setState(state);
        tecMenus.refresh();
        manageMenus.refresh();
    }

    private void initializeControl() {
        tecMenus.setCellFactory(cf -> new MenuListCell(true));
        tecMenus.getSelectionModel().selectedItemProperty()
                .addListener((observable, oldValue, newValue) -> {
                    if (Objects.nonNull(newValue)) {
                        manageMenus.getSelectionModel().clearSelection();
                        loadContent(newValue);
                    }
                });
        manageMenus.setCellFactory(cf -> new MenuListCell(true));
        manageMenus.getSelectionModel().selectedItemProperty()
                .addListener((observable, oldValue, newValue) -> {
                    if (Objects.nonNull(newValue)) {
                        tecMenus.getSelectionModel().clearSelection();
                        loadContent(newValue);
                    }
                });
    }

    public void refreshFinishStateByLayerTarget() {
        var state = systemProcessService.findOverallEvalProcess(this.currentSystemId)
                .stream()
                .filter(ps -> StringUtils.equals(ps.getName(), EvaluationModule.fromNameByOverallEval(currentLayerTarget.getTitle()).getName()))
                .map(SystemProcessDTO::getFinishState)
                .findFirst()
                .orElse(FinishState.NONE);
        refreshLayerFinishState(currentLayerTarget, state);
    }

    private void loadMenuData() {
        LogUtils.info(log, "获取层面指标树节点信息...");
        LogUtils.record(log, "请求数据:{}", this.currentSystemId);
        CompletableFuture.supplyAsync(() -> systemTargetService.findLayerTarget(this.currentSystemId))
                .thenAccept(res -> {
                    List<SystemProcessDTO> processDTOS = systemProcessService.findOverallEvalProcess(this.currentSystemId);
                    Platform.runLater(() -> {
                        if (res.isSuccess()) {
                            this.resultCorrectionPane.setVisible(true);
                            this.emptyPane.setVisible(false);
                            this.initMenu(res.getData(), processDTOS);
                        } else {
                            this.resultCorrectionPane.setVisible(false);
                            this.emptyPane.setVisible(true);
                            this.emptyLabel.setText(res.getMsg());
                        }
                    });
                })
                .exceptionally((ex) -> {
                    log.error("获取层面指标树节点信息出错!", ex);
                    return null;
                });
    }
    private void initMenu(List<LayerTargetDTO> targets, List<SystemProcessDTO> process){
        tecMenus.getItems().clear();
        manageMenus.getItems().clear();
        targets.stream().filter(t->t.getType() == TargetType.TECHNOLOGY)
                .sorted(Comparator.comparingInt(LayerTargetDTO::getSort))
                .forEach(lt-> renderMenuItem(lt,tecMenus,process));

        targets.stream().filter(t->t.getType() == TargetType.MANAGEMENT)
                .sorted(Comparator.comparingInt(LayerTargetDTO::getSort))
                .forEach(lt-> renderMenuItem(lt,manageMenus,process));
        tecMenus.getSelectionModel().select(0);
    }
    private void renderMenuItem(LayerTargetDTO lt,ListView<MenuVO> menus, List<SystemProcessDTO> process){
        FinishState finishState = process.stream()
                .filter(sp -> StringUtils.contains(sp.getName(), lt.getName()))
                .map(SystemProcessDTO::getFinishState)
                .findFirst().orElse(FinishState.NONE);
        var item = new MenuVO(0,lt.getTargetId(),lt.getName(),ControlUtils.finishStateToIcon(finishState));
        item.setState(finishState);
        menus.getItems().add(item);
    }

    private void loadContent(MenuVO menuLabel){
        this.currentLayerTarget = menuLabel;
        var evalCorrectionView = AppStore.getEvaluationView(this.currentSystemId, EvalCorrectionView.class);
        if(evalCorrectionView.getController() instanceof EvalCorrectionController controller){
            controller.initializeData(this.currentSystemId,this.currentLayerTarget,this.page);
        }
    }

}